<template>
    <div>
        <!-- <searchForm :searchArr="searchArr" @onSubmit="onSubmit">
            <template #sbuName="{ item }">
                <el-select
                    v-model="item.value"
                    placeholder="请选择"
                    style="width: 100%"
                    :clearable="true"
                    filterable
                    remote
                    :remote-method="getSbuData"
                >
                    <el-option
                        v-for="item in sbuOptions"
                        :key="item.sbuName"
                        :label="item.sbuName"
                        :value="item.sbuName"
                    />
                </el-select>
            </template>
        </searchForm> -->
        <div class="gva-table-box">
            <div class="role">
                <LTable
                    tableName="productStyle"
                    :columns="columns"
                    :tableData="tableData"
                    :pages="pages"
                    :maxHeight="'calc(100vh - 226px)'"
                    :searchArr="searchArr"
                    :isSearch="true"
                    @onSubmit="onSubmit"
                    @updateMultipleSelection="handleSelectionChange"
                    @changePages="changePages"
                    @rowDblclick="
                        (v) => {
                            getDetails(v, 'v');
                        }
                    "
                    :export="true"
                >
                    <!-- <template #CreatedAt="{ row }">
                        {{ formatDate(row.CreatedAt) }}
                    </template>
                    <template #UpdatedAt="{ row }">
                        {{ formatDate(row.UpdatedAt) }}
                    </template> -->
                    <!-- <template #styleNum="scope">
                        <el-popover
                            placement="right"
                            :width="80"
                            trigger="hover"
                        >
                            <template #reference>
                                {{ scope.row.styleNum }}
                            </template>
                            <div class="m-action-btns">
                                <el-button
                                    type="primary"
                                    link
                                    icon="edit"
                                    class="table-button"
                                    @click="getDetails(scope.row)"
                                >
                                    编辑
                                </el-button>
                                <el-button
                                    type="primary"
                                    link
                                    icon="delete"
                                    @click="deleteRow(scope.row)"
                                    >删除</el-button
                                >
                                <relatedBtn
                                    :row="scope.row"
                                    :modalType="'productStyles'"
                                />
                                <el-button type="primary" link icon="discount"
                                    >历史快照</el-button
                                >
                            </div>
                        </el-popover>
                    </template> -->
                    <!-- <template #status="{ row }">
                        {{ row.status === "1" ? "已確認" : "草稿" }}
                    </template> -->
                    <template #action>
                        <div class="gva-btn-list" v-if="userStore.userInfo.authority?.authorityId !== 1000">
                            <el-button
                                type="primary"
                                icon="plus"
                                @click="openCreateAndEdit"
                                >新增</el-button
                            >
                            <el-button
                                icon="delete"
                                style="margin-left: 10px"
                                v-auth="btnAuth.batchDel"
                                :disabled="!multipleSelection.length"
                                @click="onDelete"
                                >删除</el-button
                            >
                            <!-- <el-button
                                :disabled="multipleSelection.length!=1"
                                type="primary"
                                icon="edit"
                                class="table-button"
                                @click="getDetails(multipleSelection.length==1&&multipleSelection[0])"
                            >
                                编辑
                            </el-button> -->
                               
                            <relatedBtn
                                :disabled="multipleSelection.length!=1"
                                :row="multipleSelection.length==1&&multipleSelection[0]"
                                :modalType="'productStyles'"
                            />
                        </div>
                        <div v-else class="gva-btn-list" style="height:22px"></div>
                    </template>
                    <!-- <template #event>
                        <el-table-column
                            align="left"
                            label="操作"
                            fixed="right"
                            min-width="320"
                            width="320"
                        >
                            <template #default="scope">
                                <el-button
                                    type="primary"
                                    link
                                    icon="edit"
                                    class="table-button"
                                    @click="getDetails(scope.row)"
                                >
                                    编辑
                                </el-button>
                                <el-button
                                    type="primary"
                                    link
                                    icon="delete"
                                    @click="deleteRow(scope.row)"
                                    >删除</el-button
                                >
                                <relatedBtn
                                    :row="scope.row"
                                    :modalType="'productStyles'"
                                />
                                <el-button type="primary" link icon="discount"
                                    >历史快照</el-button
                                >
                            </template>
                        </el-table-column>
                    </template> -->
                </LTable>
            </div>
        </div>

          <!-- 新增款式弹窗 -->
          <el-dialog
            v-model="editReasonDialogShow"
            destroy-on-close
            width="50%"
            title="新增款式资讯"
        >
            <el-form ref="addDialogRef"  :model="addForm" >
                <el-row>
                    <el-col :span="24" v-if="multipleSelection.length==1">
                        <el-form-item :label="`${il8n('xiangmubianhao.label')}：`">
                          {{addForm.projectNum  }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" v-else>
                          <!-- 项目编号 -->
                          <el-form-item
                            :label="`${il8n('xiangmubianhao.label')}：`"
                            prop="projectNum"
                        >
                            <el-select
                                v-model="addForm.projectNum"
                                :placeholder="`${il8n(
                                    'xiangmubianhao.placeholder'
                                )}`"
                                style="width: 100%"
                                filterable
                                remote
                                :remote-method="remoteMethodProject"
                            >
                                <el-option
                                    v-for="(item, key) in projectListOptions"
                                    :key="key"
                                    :label="item.projectNum"
                                    :value="item.projectNum"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="创建数量：">
                            <el-input-number v-model="addForm.num"  :max="99" :min="1" :precision="0"
                            :controls="false" :clearable="false" placeholder="请输入"  />
                        </el-form-item>
                    </el-col>
                   
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="save"
                        >确定</el-button
                    >
                    <el-button @click="closeDialog"
                        >取消</el-button
                    >
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {
    createProductStyles,
    deleteProductStyles,
    deleteProductStylesByIds,
    updateProductStyles,
    findProductStyles,
    getProductStylesList,
} from "@/api/plmProductStyles";
import {
    findSbuProjects,
} from "@/api/plmSbuProjects";
import { getSysDictionaryDetailList } from "@/api/sysDictionaryDetail"; // 获取字典
import { getSbuDataList } from "@/api/confSbuData";
import { getSbuProjectsList } from "@/api/plmSbuProjects";
// 全量引入格式化工具 请按需保留
import {
    getDictFunc,
    formatDate,
    formatBoolean,
    filterDict,
    ReturnArrImg,
    onDownloadFile,
} from "@/utils/format";
import { useDict } from "@/utils/dictionary.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, computed, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
// 引入组件
import LTable from "@/components/LTable/LTable.vue";
import { useI18n } from "vue-i18n";
const { t: il8n } = useI18n();
import { useBtnAuth } from "@/utils/btnAuth";
const btnAuth = useBtnAuth();
import { useUserStore } from '@/pinia/modules/user'
const userStore = useUserStore()

defineOptions({
    name: "ProductStyles",
});
// 路由操作
const router = new useRouter();
const route = new useRoute();


// 自动化生成的字典（可能为空）以及字段
const formData = ref({
    styleNum: "",
    projectNum: "",
    cumstomerNum: "",
    customerStyleNum: "",
    updateUser: "",
    UpdatedAt: new Date(),
    status: "",
});



// 验证规则
const rule = reactive({});

// =========== 表格控制部分 ===========
const tableData = ref([]);
const pages = ref({
    page: 1,
    pageSize: 20,
    total: 0,
});
const searchInfo = ref({});

const CreatedAtFilters = computed(() => {
    return tableData.value.map((item) => {
        return { text: formatDate(item.CreatedAt), value: item.CreatedAt };
    });
});
const UpdatedAtFilters = computed(() => {
    return tableData.value.map((item) => {
        return { text: formatDate(item.UpdatedAt), value: item.UpdatedAt };
    });
});

// ======表格头部数据======
const columns = ref([
    {
        prop: "styleNum",
        label: "款式编号",
        fixedWidth: 130,
        show: true,
        filter: true,
        isSearch:true,
        // slot: "styleNum",
        tableColumnProps: {
            fixed: "left",
        },
    },
    {
        prop: "sbuNum",
        label: "SBU",
        fixedWidth: 100,
        show: true,
        filter: true,
        isSearch:true,
    },
    {
        prop: "cumstomerNum",
        label: "客户编号",
        fixedWidth: 120,
        show: true,
        filter: true,
        isSearch:true,
    },
    {
        prop: "customerBrand",
        label: "品牌",
        fixedWidth: 130,
        show: true,
        filter: true,
        isSearch:true,
    },
    {
        prop: "localStyleNum",
        label: "本厂款号",
        fixedWidth: 160,
        show: true,
        filter: true,
        isSearch:true,
    },
    {
        prop: "status",
        label: "状态",
        fixedWidth: 90,
        show: true,
        filter: true,
        isSearch:true,
        // slot: "status",
    },
    {
        prop: "frameMaterial",
        label: "镜架材质",
        fixedWidth: 120,
        show: true,
        filter: true,
        isSearch:true,
        selectList: [],
    },

    {
        prop: "customerStyleNum",
        label: "客户款号",
        fixedWidth: 120,
        show: true,
        filter: true,
        isSearch:true,
    },
    // {
    //     prop: "frameCate",
    //     label: "架类",
    //     fixedWidth: 120,
    //     show: true,
    //     filter: true,
    //     isSearch:true,
    // },
    {
        prop: "glassFrameCate",
        label: "镜架类别",
        fixedWidth: 120,
        show: true,
        filter: true,
        isSearch:true,
    },
    {
        prop: "peLeader",
        label: "工程师组长",
        fixedWidth: 130,
        show: true,
        filter: true,
        isSearch:true,
    },
    // {
    //     prop: "gender",
    //     label: "性别",
    //     fixedWidth: 90,
    //     show: true,
    //     filter: true,
    //     isSearch:true,
    // },
    {
        prop: "CreatedAt",
        label: "创建时间",
        fixedWidth: 130,
        show: true,
        filter: true,
        isSearch:true,
    },
    {
        prop: "createUser",
        label: "创建人",
        fixedWidth: 100,
        show: true,
        filter: true,
        isSearch:true,
    },
    {
        prop: "UpdatedAt",
        label: "更新时间",
        fixedWidth: 130,
        show: true,
        filter: true,
        isSearch:true,
    },
    {
        prop: "updateUser",
        label: "更新人",
        fixedWidth: 100,
        show: true,
        filter: true,
        isSearch:true,
    },
]);
// ======查询数据======
const searchArr = ref([
    {
        prop: "styleNum",
        label: "款式编号",
        show: true, // 通过 show 来控制列的展示或隐藏
        value: "",
        type: "input",
    },
    {
        prop: "sbuNum",
        label: "SBU",
        show: true,
        value: "",
        type: "input",
        slot: "sbuName",
    },
    {
        prop: "cumstomerNum",
        label: "客户编号",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "customerBrand",
        label: "品牌",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "customerStyleNum",
        label: "客户款号",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "localStyleNum",
        label: "本厂款号",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "frameMaterial",
        label: "镜架材质",
        show: true,
        value: undefined,
        type: "select",
        selectList: [],
    },
    {
        prop: "glassFrameCate",
        label: "镜架类别",
        show: true,
        value: undefined,
        type: "select",
        selectList: [],
    },
    // {
    //     prop: "frameCate",
    //     label: "架类",
    //     show: true,
    //     value: undefined,
    //     type: "select",
    //     selectList: [],
    // },
    // {
    //     prop: "gender",
    //     label: "性别",
    //     show: true,
    //     value: undefined,
    //     type: "select",
    //     selectList: [],
    // },
    {
        prop: "peLeader",
        label: "工程师组长",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "status",
        label: "状态",
        show: true,
        value: undefined,
        type: "select",
        selectList: [
            { label: "草稿", value: "0" },
            { label: "已確認", value: "1" },
        ],
    },
    {
        prop: "CreatedAt",
        label: "创建时间",
        show: true,
        value: "",
        type: "datetimerange",
    },
    {
        prop: "createUser",
        label: "创建人",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "UpdatedAt",
        label: "更新时间",
        show: true,
        value: "",
        type: "datetimerange",
    },
    {
        prop: "updateUser",
        label: "更新人",
        show: true,
        value: "",
        type: "input",
    },
]);

// 重置
const onReset = () => {
    searchInfo.value = {};
    getTableData();
};

// 搜索
const onSubmit = (val) => {
    searchInfo.value = {
        ...val,
    };
    // if (searchInfo.value.CreatedAt) {
    //     searchInfo.value["startCreatedAt"] =
    //         searchInfo.value.CreatedAt[0] || "";
    //     searchInfo.value["endCreatedAt"] = searchInfo.value.CreatedAt[1] || "";
    // }
    // if (searchInfo.value.UpdatedAt) {
    //     searchInfo.value["startUpdatedAt"] =
    //         searchInfo.value.UpdatedAt[0] || "";
    //     searchInfo.value["endUpdatedAt"] = searchInfo.value.UpdatedAt[1] || "";
    // }
    pages.value.page = 1;
    pages.value.pageSize = 20;
    getTableData();
};

// 改变页码
const changePages = (currentPages) => {
    pages.value = {
        ...pages.value,
        ...currentPages,
    };
    getTableData();
};

// 查询
const getTableData = async () => {
    const table = await getProductStylesList(
        {
            page: pages.value.page,
            pageSize: pages.value.pageSize,
            ...searchInfo.value,
        },
        false
    );
    if (table.code === 0) {
        tableData.value = table.data.list.map((item) => {
            item.CreatedAt = item.CreatedAt ? formatDate(item.CreatedAt) : "";
            item.UpdatedAt = item.UpdatedAt ? formatDate(item.UpdatedAt) : "";
            if(item.peLeadUser && item.peLeadUser.nickName){
                item['peLeader'] = item.peLeadUser.nickName
            }
            // item["updateUser"] = item.updatedBySysUser?.userName;
            item.status=item.status==1?'已確認':'草稿'
            return item;
        });
        pages.value.total = table.data.total;
        pages.value.page = table.data.page;
        pages.value.pageSize = table.data.pageSize;
    }
};

// getTableData();

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => {};

// 获取需要的字典 可能为空 按需保留
setOptions();

// 多选数据
const multipleSelection = ref([]);
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        deleteProductStylesFunc(row);
    });
};

// 多选删除
const onDelete = async () => {
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(async () => {
        const IDs = [];
        if (multipleSelection.value.length === 0) {
            ElMessage({
                type: "warning",
                message: "请选择要删除的数据",
            });
            return;
        }
        multipleSelection.value &&
            multipleSelection.value.map((item) => {
                IDs.push(item.ID);
            });
        const res = await deleteProductStylesByIds({ IDs });
        if (res.code === 0) {
            ElMessage({
                type: "success",
                message: "删除成功",
            });
            if (tableData.value.length === IDs.length && pages.value.page > 1) {
                pages.value.page--;
            }
            getTableData();
        }
    });
};

// 行为控制标记（弹窗内部需要增还是改）
const type = ref("");

// 更新行
const updateProductStylesFunc = async (row) => {
    // const res = await findProductStyles({ ID: row.ID });
    type.value = "update";
    router.push({
        path: "/layout/productStylesAdd",
        query: { id: row.ID },
    });
};

// 删除行
const deleteProductStylesFunc = async (row) => {
    const res = await deleteProductStyles({ ID: row.ID });
    if (res.code === 0) {
        ElMessage({
            type: "success",
            message: "删除成功",
        });
        if (tableData.value.length === 1 && pages.value.page > 1) {
            pages.value.page--;
        }
        getTableData();
    }
};

// 打开详情
const getDetails = async (row, action) => {
    router.push({
        path: "/layout/ProductStylesView",
        query: {
            id: row.ID,
            action,
            subTitle: "款" + row.styleNum,
        },
    });
};

// 打开 新增、编辑
const openCreateAndEdit = () => {
    type.value = "create";
    editReasonDialogShow.value = true
    if(multipleSelection.value.length==1) {
        addForm.value.projectNum = multipleSelection.value[0].projectNum
    }else {
        addForm.value.projectNum = ''
    }
};

// 相关
const currentRow = ref({});
const dialogVisible = ref(false);
const relatedFun = (row) => {
    dialogVisible.value = true;
    currentRow.value = row;
};

// sub列表
const sbuOptions = ref([]);
// 获取sbu列表
const getSbuData = async (keyword) => {
    await getSbuDataList({ page: 1, pageSize: 100, sbuName: keyword }).then(
        (res) => {
            if (res.code === 0) {
                sbuOptions.value = res.data.list;
            }
        }
    );
};

// 新增款式改版---------------------------------------------------------------
const editReasonDialogShow = ref(false);
const projectListOptions = ref([]); // 项目编号列表
const addForm = ref({
    projectNum:'',
    num:1,
});

// 查询项目编号列表
const remoteMethodProject = async (keyword) => {
    const table = await getSbuProjectsList({
        page: 1,
        pageSize: 30,
        projectNum: keyword ? keyword : undefined,
    });
    if (table.code === 0) {
        projectListOptions.value = table.data.list;
    }
};

// 关弹窗
const closeDialog = ()=>{
    editReasonDialogShow.value = false
    addForm.value = {
    projectNum:'',
    num:1,
};
}

// 新增提交
const save =async () =>{
    if(!addForm.value.projectNum) {
        ElMessage({
            type: "warning",
            message: "项目编号不能为空",
        });
        return;
    }
    const projectsRes = await findSbuProjects({ projectNum: addForm.value.projectNum });
    const {sbuName,customerName,brandName} = projectsRes.data.resbuProjects

    for (let index = 0; index < addForm.value.num; index++) {
       let res = await createProductStyles({projectNum: addForm.value.projectNum,sbuNum:sbuName,cumstomerNum:customerName,customerBrand:brandName,status:'0'});

       if(index==addForm.value.num-1) {
        if(addForm.value.num==1) {
            closeDialog()
            router.push({
        path: "/layout/ProductStylesView",
        query: {
            id: res.data.ID,
            action:'nov',
            subTitle: "款" + res.data.styleNum,
        },
    });
        }else {
            getTableData();
        closeDialog()
        }
     
       }
    }
}

onMounted(async () => {
    useDict(
        "frameMaterials",
        "glassFrameCate",
        "frameCate",
        "productGender"
    ).then((d) => {
        // 字典列表
        let list = searchArr.value.map((item) => {
            if (item.prop == "frameMaterial") {
                item["selectList"] = [...d.frameMaterials];
            }
            if (item.prop == "glassFrameCate") {
                item["selectList"] = [...d.glassFrameCate];
            }
            // if (item.prop == "frameCate") {
            //     item["selectList"] = [...d.frameCate];
            // }
            // if (item.prop == "gender") {
            //     item["selectList"] = [...d.productGender];
            // }
            return item;
        });
        searchArr.value = [];
        searchArr.value = [...list];
    });
});
watch(() => route.path, (newPath, oldPath) => {
//   console.log('路由已变更：', `从 ${oldPath} 到 ${newPath}`);
    if(newPath == '/layout/productStyles'){
        getTableData();
    }
},{immediate:true});
</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");

:deep(.el-input-number .el-input__inner) {
    text-align: left;
    padding: 0 11px;
}
</style>
